// pages/exercise/exercise.js
var sliderWidth = 100; // 需要设置slider的宽度，用于计算中间位置
const apiserverUrl = require('../../config').apiserverUrl;
const ExamQuestionsListUrl = require('../../config').ExamQuestionsListUrl;
const ChapterQuestionsListUrl = require('../../config').ChapterQuestionsListUrl;
const UserTrainingWQListUrl = require('../../config').UserTrainingWQListUrl;
const UserExamWQListUrl = require('../../config').UserExamWQListUrl;
const AddTrainingWQUrl = require('../../config').AddTrainingWQUrl;
const DelTrainingWQUrl = require('../../config').DelTrainingWQUrl;
const StartExamUrl = require('../../config').StartExamUrl;
const AnswerExamUrl = require('../../config').AnswerExamUrl;
const GetUserExamQuestionUrl = require('../../config').GetUserExamQuestionUrl;
const ExamSheetUrl = require('../../config').ExamSheetUrl;

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ["答题模式", "背题模式"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    listtype: "",
    key: 0,
    qlist: [],
    sheetList: [],
    userInfo: [],
    currentIndex: 0,
    loading: true,
    useranswer: "",
    totalcount: 0,
    totalpage: 0,
    page: 1,
    limit: 100,
    loadbysheet: false,
    preIndex:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userInfo: app.globalData.userInfo,
      listtype: options.type,
      key: options.key
    });

    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });
    this.getList();
  },
  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id,
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //生命周期函数--监听页面显示
  onShow: function () {
    //console.log(this);
  },
  //生命周期函数--监听页面初次渲染完成
  onReady: function () {
    //console.log(this);
  },
  swiperchange: function (event) {
    if (event.detail.source == "touch") {
      var lastqindex = this.data.limit - 1;
      if (this.data.page == this.data.totalpage) {
        lastqindex = this.data.totalcount - (this.data.totalpage - 1) * this.data.limit - 1;
      }
      //console.log("lastqindex:" + lastqindex);
      //console.log("this.data.currentIndex:" + this.data.currentIndex);
      //console.log("event.detail.current:" + event.detail.current);
      if (this.data.currentIndex == 0 && event.detail.current == lastqindex) {
        if (this.data.page==1)//首页不再向上翻页
        {          
          wx.showModal({
            content: '已到最前',
            showCancel: false
          });
          this.setData({ currentIndex: 0, preIndex: 0 });
          return;
        }
        //上一页
        if (this.data.page > 1 && this.data.totalpage > 1) {
          this.setData({
            loadbysheet: false,
            currentIndex: this.data.limit - 1,
            page: this.data.page - 1
          });
          this.getList();
        } else {
          this.setData({ currentIndex: lastqindex });
          //获取用户答案选项接口
          //this.getUserAnswer();
        }
        this.setData({ preIndex: 0 });
      } else if (this.data.currentIndex == lastqindex && event.detail.current == 0) {
        if (this.data.page == this.data.totalpage)//末页不再向下翻页
        {
          wx.showModal({
            content: '已到最后',
            showCancel: false
          });
          this.setData({ currentIndex: lastqindex });
          return;
        }
        //下一页
        if ((this.data.page + 1) <= this.data.totalpage && this.data.totalpage > 1) {
          this.setData({
            loadbysheet: false,
            currentIndex: 0,
            page: this.data.page + 1
          });
          this.getList();
        } else {
          this.setData({ currentIndex: 0 });
          //获取用户答案选项接口
          //this.getUserAnswer();
        }
        this.setData({ preIndex: 0 });
      }
      else {
        //console.log("在当前页面上");
        this.setData({
          currentIndex: event.detail.current,
          useranswer: this.data.qlist[event.detail.current].useranswer
        });
        //获取用户答案选项接口
        //this.getUserAnswer();
      }
      //防止swiper控件卡死
      if (this.data.currentIndex == 0 && this.data.preIndex>1)
      {
        this.setData({ currentIndex: this.data.preIndex});
      }
      else
      {
        this.setData({ preIndex: this.data.currentIndex });
      }
    }
  },
  getList: function () {
    var postData;
    if (this.data.listtype == "training") {
      postData = {
        method: "GET",
        url: ExamQuestionsListUrl,
        data: {
          papersid: this.data.key,
          userid: this.data.userInfo.userid,
          isexam: 0,
          page: this.data.page,
          limit: this.data.limit,
          loading: this.data.loading
        }
      };
      this.addTraingRecord(this.data.key, 2);
    } else if (this.data.listtype == "chapter") {
      postData = {
        method: "GET",
        url: ChapterQuestionsListUrl,
        data: {
          chapter: this.data.key,
          userid: this.data.userInfo.userid,
          page: this.data.page,
          limit: this.data.limit,
          loading: this.data.loading
        }
      };
      this.addTraingRecord(this.data.key, 3);
    } else if (this.data.listtype == "trainingwq") {
      //练习错题
      postData = {
        method: "GET",
        url: UserTrainingWQListUrl,
        data: {
          userid: this.data.userInfo.userid,
          page: this.data.page,
          limit: this.data.limit,
          loading: this.data.loading
        }
      };
    } else if (this.data.listtype == "examwq") {
      //考试错题
      postData = {
        method: "GET",
        url: UserExamWQListUrl,
        data: {
          papersid: this.data.key,
          userid: this.data.userInfo.userid,
          page: this.data.page,
          limit: this.data.limit,
          loading: this.data.loading
        }
      };
    }
    wx.request({
      method: "post",//请求数据用get，添加数据post，修改数据put
      url: apiserverUrl,
      data: postData,
      header: {
        "Content-Type": "application/json"
      },
      success: res => {
        if (res.data.IsSuccess) {
          this.setData({
            page: res.data.Data.page,
            totalcount: res.data.Data.totalcount,
            totalpage: res.data.Data.totalpage,
            qlist: res.data.Data.qlist,
            useranswer: res.data.Data.qlist[0].useranswer
          });
          if (this.data.loading) {
            this.setData({
              loading: false,
              currentIndex: res.data.Data.qindex,
              useranswer: this.data.qlist[res.data.Data.qindex].useranswer
            });
          }
          //this.getUserAnswer();
        }
      }
    });
  },
  qnum_click: function (e) {
    var page = parseInt(e.currentTarget.id / this.data.limit);
    if (page == 0) {
      page = 1;
    } else {
      page = page + 1;
    }
    this.setData({ currentIndex: (e.currentTarget.id - (page - 1) * this.data.limit) });
    if (page != this.data.page) {
      this.setData({
        loadbysheet: true,
        page: page
      });
      this.getList();
    } 
    this.setData({
      useranswer: this.data.qlist[this.data.currentIndex].useranswer
    });
  },
  answer_click: function (e) {
    this.setData({ useranswer: e.currentTarget.dataset.sn });
    if (this.data.listtype == "training" || this.data.listtype == "chapter") {
      var modeltype = this.data.listtype == "training" ? 2 : 3;
      var err = this.data.qlist[this.data.currentIndex].answer == this.data.useranswer ? 1 : 2;

      var questionindex = this.data.currentIndex;
      if (this.data.page > 1) {
        questionindex = (this.data.page - 1) * this.data.limit + this.data.currentIndex
      }
      //添加选择记录接口
      wx.request({
        method: "post",//请求数据用get，添加数据post，修改数据put
        url: apiserverUrl,
        data: {
          method: "GET", url: AnswerExamUrl, data: {
            papersid: this.data.key,
            userid: this.data.userInfo.userid,
            modeltype: modeltype,
            questionindex: questionindex,
            questionid: e.currentTarget.dataset.qid,
            answer: this.data.useranswer,
            err: err
          }
        },
        header: {
          "Content-Type": "application/json"
        },
        success: res => {
          if (res.data.IsSuccess) {
            this.data.qlist[this.data.currentIndex].useranswer = this.data.useranswer;
            this.setData({
              qlist: this.data.qlist
            });
          }
        }
      });
      // if (this.data.qlist[this.data.currentIndex].answer != this.data.useranswer) {
      //   //添加至错题集
      //   wx.request({
      //     method: "post",
      //     url: apiserverUrl,
      //     data: {
      //       method: "GET",
      //       url: AddTrainingWQUrl,
      //       data: {
      //         userid: this.data.userInfo.userid,
      //         questionid: e.currentTarget.dataset.qid,
      //         answer: this.data.useranswer
      //       }
      //     },
      //     header: {
      //       "Content-Type": "application/json"
      //     }
      //   });
      // }
    }
    //else if (this.data.listtype == "trainingwq") {
    //   if (this.data.qlist[this.data.currentIndex].answer == this.data.useranswer) {
    //     wx.request({
    //       method: "post",
    //       url: apiserverUrl,
    //       data: {
    //         method: "GET",
    //         url: DelTrainingWQUrl,
    //         data: {
    //           userid: this.data.userInfo.userid,
    //           questionid: e.currentTarget.dataset.qid
    //         }
    //       },
    //       header: {
    //         "Content-Type": "application/json"
    //       },
    //       success: res => {
    //         if (res.data.IsSuccess) {
    //           var postData = {
    //             method: "GET",
    //             url: UserTrainingWQListUrl,
    //             data: {
    //               userid: this.data.userInfo.userid
    //             }
    //           };
    //           this.getList(postData);
    //         }
    //       }
    //     });
    //   }
    // }
  },
  showPopup() {
    var modeltype = 0;
    if (this.data.listtype == "training" || this.data.listtype == "chapter") {
      modeltype = this.data.listtype == "training" ? 2 : 3;
    } else if (this.data.listtype == "trainingwq") {
      modeltype = 4;
    } else {
      modeltype = 5;
    }
    //console.log(this.data.key);
    //获取用户答题卡接口
    wx.request({
      method: "post",//请求数据用get，添加数据post，修改数据put
      url: apiserverUrl,
      data: {
        method: "GET", url: ExamSheetUrl, data: {
          papersid: this.data.key,
          userid: this.data.userInfo.userid,
          modeltype: modeltype
        }
      },
      header: {
        "Content-Type": "application/json"
      },
      success: res => {
        if (res.data.IsSuccess) {
          // console.log(res.data.Data.examsheet);
          this.setData({
            sheetList: res.data.Data.examsheet
          });
          let popupComponent = this.selectComponent('.J_Popup');
          popupComponent && popupComponent.show();
        }
      }
    });
  },
  addTraingRecord: function (papersid, modeltype) {
    //开始考试接口
    wx.request({
      method: "post",//请求数据用get，添加数据post，修改数据put
      url: apiserverUrl,
      data: {
        method: "GET", url: StartExamUrl, data: {
          papersid: papersid,
          userid: this.data.userInfo.userid,
          modeltype: modeltype
        }
      },
      header: {
        "Content-Type": "application/json"
      }
    });
  },
  getUserAnswer: function () {
    var modeltype = 0;
    if (this.data.listtype == "training" || this.data.listtype == "chapter") {
      modeltype = this.data.listtype == "training" ? 2 : 3;
    } else if (this.data.listtype == "trainingwq") {
      modeltype = 4;
    } else {
      modeltype = 5;
    }

    wx.request({
      method: "post",//请求数据用get，添加数据post，修改数据put
      url: apiserverUrl,
      data: {
        method: "GET", url: GetUserExamQuestionUrl, data: {
          papersid: this.data.key,
          userid: this.data.userInfo.userid,
          modeltype: modeltype,
          questionid: this.data.qlist[this.data.currentIndex].id
        }
      },
      header: {
        "Content-Type": "application/json"
      },
      success: res => {
        this.setData({ useranswer: "" });
        if (res.data.IsSuccess && res.data.Data != null) {
          this.setData({ useranswer: res.data.Data.answer });
        } else {
          this.setData({ useranswer: "" });
        }
      }
    });
  },
})